<?php
//
//	file: includes/ucp/ucp_attach_search.php
//	author: ptirhiik
//	begin: 03/03/2006
//	version: 1.6.3 - 13/06/2007
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//
//	based on : attachment_mod copyright (c) 2002 Meik Sievertsen (acydburn)
//

if ( !defined('IN_PHPBB') )
{
	die('Hack attempt');
}

if ( !class_exists('forums') )
{
	include($config->url('includes/class_forums'));
}
include_once($config->url('includes/attach/class_attach_cp_fields'));
include_once($config->url('includes/attach/class_attach_parent'));

// search form
$available_sort = array(
	'filename' => 'Sort_Filename',
	'comment' => 'Sort_Comment',
	'extension' => 'Sort_Extension',
	'filesize' => 'Sort_Size',
	'downloads' => 'Sort_Downloads',
	'posttime' => 'Sort_Posttime',
);
$sort_fields = array(
	'filename' => 'd.real_filename',
	'comment' => 'd.file_comment',
	'extension' => 'd.extension',
	'filesize' => 'd.filesize',
	'downloads' => 'd.download_count',
	'posttime' => 'd.filetime',
);
$available_order = array(
	'' => 'Sort_Ascending',
	'desc' => 'Sort_Descending',
);
$order_fields = array(
	'' => '',
	'desc' => ' DESC',
);
$dft_sort = 'posttime';
$dft_order = 'desc';

$topicdays_list = array(0 => 'All_Attachments', 1 => '1_Day', 7 => '7_Days', 14 => '2_Weeks', 30 => '1_Month', 90 => '3_Months', 180 => '6_Months', 364 =>'1_Year');

// get the forums list selection
if ( $forums === false )
{
	if ( !class_exists('forums') )
	{
		include($config->url('class_forums'));
	}
	$forums = new forums();
	$forums->read();
}
if ( empty($user->cache[POST_FORUM_URL]) )
{
	$user->get_cache(POST_FORUM_URL);
}

$fields = array(
	'filename' => array('type' => 'attach_search_username', 'legend' => 'File_name', 'explain' => 'Search_wildcard_explain'),
	'file_comment' => array('type' => 'attach_search_username', 'legend' => 'File_comment', 'explain' => 'Search_wildcard_explain'),
	'sizemin' => array('type' => 'attach_filesize', 'legend' => 'Size_between'),
	'sizemax' => array('type' => 'attach_filesize', 'combined' => true, 'linefeed' => true),
	'countmin' => array('type' => 'int', 'legend' => 'Count_between'),
	'countmax' => array('type' => 'int', 'combined' => true, 'linefeed' => true),
	'topicdays' => array('type' => 'list', 'legend' => 'More_days_old', 'options' => $topicdays_list),
	'sort' => array('type' => 'list', 'legend' => 'Sort_by', 'options' => $available_sort, 'value' => $dft_sort),
	'order' => array('type' => 'list', 'combined' => true, 'options' => $available_order, 'value' => $dft_order),
);

class attach_cp extends form
{
	var $requester;
	var $parms;

	var $data;
	var $total;
	var $ppage;
	var $start;
	var $now;

	var $delete_box;
	var $post_ids;
	var $privmsgs_ids;

	var $handler;

	function attach_cp($requester, $parms='', &$fields)
	{
		global $config;

		$this->requester = $requester;
		$this->parms = empty($parms) ? array() : $parms;
		$this->data = array();
		$this->total = 0;
		$this->ppage = 0;
		$this->start = 0;
		$this->now = time();

		$this->delete_box = array();
		$this->post_ids = array();
		$this->privmsgs_ids = array();

		$this->handler = new file_handler($config->globals['mod_attachment_CH']['config']->data);

		parent::form($fields);
	}

	function process()
	{
		if ( $this->init() )
		{
			$this->check();
			$this->validate();
			$this->display();
			return true;
		}
		return false;
	}

	function init()
	{
		global $config;

		$this->start = _read('start', TYPE_INT);
		$this->ppage = _read('ppage', TYPE_INT, intval($config->data['topics_per_page']));
		$this->read();
		return true;
	}

	function check()
	{
	}

	function validate()
	{
		global $error, $error_msg;
		global $config, $user, $db;

		$done = false;

		$this->delete_box = array();
		$this->post_ids = array();
		$this->privmsgs_ids = array();
		$delete = _read('delete_details', TYPE_INT);
		if ( $delete && !_button('cancel_delete') && !empty($this->data) )
		{
			$confirm = _button('confirm_delete');
			$delete_box = get_var('delete_box', array(0));
			$delete_box = empty($delete_box) ? array() : array_flip($delete_box);
			$attach_ids = get_var('attach_ids', array(0));
			$post_ids = get_var('post_ids', array(0));
			$privmsgs_ids = get_var('privmsgs_ids', array(0));

			$files = array();
			if ( !empty($this->data) )
			{
				foreach ( $this->data as $idx => $data )
				{
					if ( isset($delete_box[ ($idx + 1) ]) && (intval($this->data[$idx]['attach_id']) == intval($attach_ids[$idx])) && (intval($this->data[$idx]['post_id']) == intval($post_ids[$idx])) && (intval($this->data[$idx]['privmsgs_id']) == intval($privmsgs_ids[$idx])) )
					{
						if ( $confirm )
						{
							$files[ intval($this->data[$idx]['attach_id']) ] = array('physical_filename' => $this->data[$idx]['physical_filename'], 'thumbnail' => intval($this->data[$idx]['thumbnail']));
							if ( intval($this->data[$idx]['post_id']) )
							{
								$this->post_ids[] = intval($this->data[$idx]['post_id']);
							}
							if ( intval($this->data[$idx]['privmsgs_id']) )
							{
								$this->privmsgs_ids[] = intval($this->data[$idx]['privmsgs_id']);
							}
						}
						else
						{
							$this->delete_box[ ($idx + 1) ] = true;
						}
					}
				}
			}
			unset($delete_box);
			unset($attach_ids);
			unset($post_ids);
			unset($privmsgs_ids);

			// do the deletetion
			if ( $confirm && !empty($files) )
			{
				// delete attachments links
				$sql_where = array();
				if ( !empty($this->post_ids) )
				{
					$sql_where[] = 'post_id IN(' . implode(', ', $this->post_ids) . ')';
				}
				if ( !empty($this->privmsgs_ids) )
				{
					$sql_where[] = 'privmsgs_id IN(' . implode(', ', $this->privmsgs_ids) . ')';
				}
				$sql = 'DELETE FROM ' . ATT_LINKS_TABLE . '
							WHERE attach_id IN(' . implode(', ', array_keys($files)) . ')' . (empty($sql_where) ? '' : '
								AND (' . implode(' OR ', $sql_where) . ')');
				unset($sql_where);
				$db->sql_query($sql, false, __LINE__, __FILE__);
				$done = true;

				// get remaining links
				$sql = 'SELECT attach_id
							FROM ' . ATT_LINKS_TABLE . '
							WHERE attach_id IN(' . implode(', ', array_keys($files)) . ')';
				$result = $db->sql_query($sql, false, __LINE__, __FILE__);
				while ( $row = $db->sql_fetchrow($result) )
				{
					unset($files[ intval($row['attach_id']) ]);
				}
				$db->sql_freeresult($result);

				// delete files
				if ( !empty($files) )
				{
					if ( $this->handler->open_channel() )
					{
						foreach ( $files as $attach_id => $data )
						{
							$this->handler->unlink($data['physical_filename'], $data['thumbnail']);
						}
						$this->handler->close_channel();
					}

					// delete desc
					$sql = 'DELETE FROM ' . ATT_DESC_TABLE . '
								WHERE attach_id IN(' . implode(', ', array_keys($files)) . ')';
					$db->sql_query($sql, false, __LINE__, __FILE__);

					// resync pms
					if ( !empty($this->privmsgs_ids) )
					{
						$sql = 'UPDATE ' . PRIVMSGS_TABLE . '
									SET privmsgs_attachment = 0
									WHERE privmsgs_id IN(' . implode(', ', $this->privmsgs_ids) .')
										AND privmsgs_id NOT IN(' . $db->sql_subquery('privmsgs_id', '
											SELECT DISTINCT privmsgs_id
												FROM ' . ATT_LINKS_TABLE . '
												WHERE privmsgs_id IN(' . implode(', ', $this->privmsgs_ids) . ')
										', __LINE__, __FILE__) . ')';
						$db->sql_query($sql, false, __LINE__, __FILE__);
					}

					// sync posts
					if ( !empty($this->post_ids) )
					{
						$sql = 'UPDATE ' . POSTS_TABLE . '
									SET post_attachment = 0
									WHERE post_id IN(' . implode(', ', $this->post_ids) .')
										AND post_id NOT IN(' . $db->sql_subquery('post_id', '
											SELECT DISTINCT post_id
												FROM ' . ATT_LINKS_TABLE . '
												WHERE post_id IN(' . implode(', ', $this->post_ids) . ')
										', __LINE__, __FILE__) . ')';
						$db->sql_query($sql, false, __LINE__, __FILE__);

						// sync topic
						$sql = 'SELECT topic_id, SUM(post_attachment) AS sum_post_attachment
									FROM ' . POSTS_TABLE . '
									WHERE topic_id IN (' . $db->sql_subquery('topic_id', '
										SELECT DISTINCT topic_id
											FROM ' . POSTS_TABLE . '
											WHERE post_id IN (' . implode(', ', $this->post_ids) . ')
										', __LINE__, __FILE__) . ')
									GROUP BY topic_id
									HAVING SUM(post_attachment) = 0';
						$result = $db->sql_query($sql, false, __LINE__, __FILE__);
						$topic_ids = array();
						while ( $row = $db->sql_fetchrow($result) )
						{
							$topic_ids[] = intval($row['topic_id']);
						}
						$db->sql_freeresult($result);
						if ( !empty($topic_ids) )
						{
							$sql = 'UPDATE ' . TOPICS_TABLE . '
										SET topic_attachment = 0
										WHERE topic_id IN(' . implode(', ', $topic_ids) . ')';
							$db->sql_query($sql, false, __LINE__, __FILE__);
						}
						unset($topic_ids);
					}
				}
			}
			unset($files);
		}

		// send message
		if ( $done )
		{
			message_return('Attachments_deleted', 'Click_return_attach_search', $config->url($this->requester, $this->parms, true));
		}
	}

	function display()
	{
		global $template, $user, $config;
		global $view_user;
		global $sort_fields, $order_fields;
		global $dft_sort, $dft_order;

		// send confirm
		if ( _button('delete_details') && !empty($this->delete_box) && !_button('cancel_delete') && !_button('confirm_delete') )
		{
			$template->assign_vars(array(
				'L_FORM' => $user->lang('Confirm'),
				'MESSAGE' => $user->lang('Confirm_delete_attachments'),
			));
			display_buttons(array(
				'confirm_delete' => array('txt' => 'Delete', 'img' => 'cmd_delete', 'key' => 'cmd_delete'),
				'cancel_delete' => array('txt' => 'Cancel', 'img' => 'cmd_cancel', 'key' => 'cmd_cancel'),
			));
			$template->set_switch('form');
			$template->assign_vars(array('FORM' => $template->include_file('ucp/ucp_confirm_box.tpl')));

			// hide delete
			_hide('delete_details', true);

			// hide selection values
			if ( !empty($this->data) )
			{
				foreach ( $this->data as $idx => $data )
				{
					if ( isset($this->delete_box[ ($idx + 1) ]) )
					{
						_hide('delete_box[]', $idx + 1, true);
					}
					_hide('attach_ids[]', $this->data[$idx]['attach_id'], true);
					_hide('post_ids[]', $this->data[$idx]['post_id'], true);
					_hide('privmsgs_ids[]', $this->data[$idx]['privmsgs_id'], true);
				}
			}

			// hide search values
			foreach ( $this->fields as $field_name => $field )
			{
				_hide($field_name, $this->fields[$field_name]->form_escape_string($this->fields[$field_name]->value));
			}
			return;
		}

		// display search form
		foreach ( $this->fields as $field_name => $field )
		{
			$this->fields[$field_name]->display();
		}
		display_buttons($this->buttons);
		$template->assign_vars(array('SEARCH_FORM' => $template->include_file('form_fields.tpl', array('field'))));

		// display details
		if ( $count_data = count($this->data) )
		{
			$color = false;
			for ( $i = 0; $i < $count_data; $i++ )
			{
				$row = $this->data[$i];
				$attach_id = intval($row['attach_id']);
				$color = !$color;
				$file_size = format_size(intval($row['filesize']));

				$topic_title_alt = !empty($row['topic_title']) ? _censor($row['topic_title']) : '';
				$topic_title = _un_htmlspecialchars($topic_title_alt);
				if ( (intval($config->data['last_topic_title_length']) > 3) && (strlen($topic_title_alt) > $config->data['last_topic_title_length']) )
				{
					$topic_title = substr($topic_title, 0, intval($config->data['last_topic_title_length'])-3) . '...';
				}
				$topic_title = _html_entities_encode($topic_title);

				$from = intval($row['user_id']) == $view_user->data['user_id'];
				$privmsgs_type = isset($row['privmsgs_type']) ? $row['privmsgs_type'] : null;
				switch( $privmsgs_type )
				{
					case PRIVMSGS_READ_MAIL:
					case PRIVMSGS_NEW_MAIL:
					case PRIVMSGS_UNREAD_MAIL:
						$pm_box = $from ? 'Outbox' : 'Inbox';
						break;
					case PRIVMSGS_SENT_MAIL:
						$pm_box = $from ? 'Sentbox' : 'Inbox';
						break;
					case PRIVMSGS_SAVED_OUT_MAIL:
						$pm_box = $from ? 'Savebox' : 'Inbox';
						break;
					case PRIVMSGS_SAVED_IN_MAIL:
						$pm_box = $from ? 'Sentbox' : 'Savebox';
						break;
					default:
						$pm_box = '';
						break;
				}

				$template->assign_block_vars('row', array(
					'ROW_NUMBER' => $i + 1,
					'ATTACH_ID' => intval($row['attach_id']),
					'POST_ID' => intval($row['post_id']),
					'PRIVMSGS_ID' => intval($row['privmsgs_id']),

					'U_FILE_NAME' => $config->url('viewtopic', array('mode' => 'attach', 'id' => intval($row['attach_id'])), true),
					'FILE_NAME' => $row['real_filename'],
					'FILE_COMMENT' => $row['file_comment'],
					'EXTENSION' => $row['extension'],
					'FILE_SIZE' => $file_size['value'],
					'UNIT' => $user->lang($file_size['unit']),
					'DOWNLOAD_COUNT' => intval($row['download_count']),
					'ATTACH_COUNT' => isset($row['count_attach_id']) ? intval($row['count_attach_id']) : 0,
					'TOPIC_TITLE' => $topic_title,
					'TOPIC_TITLE_ALT' => $topic_title_alt,
					'U_VIEW_POST' => intval($row['post_id']) ? $config->url('viewtopic', array(POST_POST_URL => intval($row['post_id'])), true, intval($row['post_id'])) : '',
					'FILE_TIME' => $user->date(intval($row['filetime'])),
					'L_PM_BOX' => $pm_box ? $user->lang($pm_box) : '',
				));
				$template->set_switch('row.light', $color);
				$template->set_switch('row.privmsgs', intval($row['privmsgs_id']));
			}
		}

		// display header
		$template->assign_vars(array(
			'L_FILE_NAME' => $user->lang('File_name'),
			'L_FILE_SIZE' => $user->lang('Filesize'),
			'L_DOWNLOAD_COUNT' => $user->lang('Downloads'),
			'L_LOCATION' => $user->lang('Posted_in_topic'),
			'L_PRIVMSGS' => $user->lang('Private_Message'),
			'L_VIEW_POST' => $user->lang('View_topic'),

			'L_NO_MATCHES' => $user->lang('No_attach_search_match'),
		));
		$template->set_switch('details');
		$details_buttons = array(
			'delete_details' => array('txt' => 'Delete_marked', 'img' => 'cmd_delete', 'key' => 'cmd_delete'),
		);
		display_buttons($details_buttons, 'details');

		$parms = $this->get_link_parms();
		$pagination = new pagination($this->requester, $parms);
		$pagination->display('pagination', $this->total, $this->ppage, $this->start, true, 'Attachments_count');
		unset($pagination);

		// send all to template
		$template->assign_block_vars('cp_content', array('BOX' => $template->include_file('ucp/ucp_attach_search_box.tpl')));

		// quota box
		$this->display_quota();
	}

	function display_quota()
	{
		global $template, $db, $user, $config;
		global $view_user;
		global $cp_no_menus, $cp_menu_title, $cp_requester, $cp_parms, $cp_panels, $menus, $sub_menus, $ctx_menus, $menu_id, $subm_id, $ctx_id;

		// we handle the menu to display it first
		$cp_no_menus = true;
		$template->assign_vars(array(
			'L_MENU' => $cp_menu_title,
		));
		$cp_panels->display_menus($menus, $sub_menus, $ctx_menus, $menu_id, $subm_id, $ctx_id, $cp_requester, $cp_parms);

		// get quota size
		$attach_parent = new attach_parent(PAGE_INDEX);
		$attach_parent->get_quota_limits($view_user->data, PAGE_INDEX);
		unset($attach_parent);
		$filesize_limit_value = doubleval($config->globals['mod_attachment_CH']['config']->data['upload_filesize_limit']) ? doubleval($config->globals['mod_attachment_CH']['config']->data['upload_filesize_limit']) : doubleval($config->globals['mod_attachment_CH']['config']->data['attachment_quota']);
		if ( empty($filesize_limit_value) )
		{
			$filesize_limit_unit = '';
			$filesize_limit = $user->lang('Unlimited');
		}
		else
		{
			$units = array();
			$filesize_limit_unit = size_get_units($filesize_limit_value, $units);
			$filesize_limit = round($filesize_limit_value / max(1, $filesize_limit_unit), 2) . ' ' . $user->lang($units[$filesize_limit_unit]);
		}

		// get upload size (only posts)
		$sql = 'SELECT SUM(d.filesize) AS sum_filesize
					FROM ' . ATT_DESC_TABLE . ' d, ' . ATT_LINKS_TABLE . ' a
					WHERE d.attach_id = a.attach_id
						AND a.user_id = ' . intval($view_user->data['user_id']) . '
						AND a.privmsgs_id = 0';
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		$filesize_upload_value = ($row = $db->sql_fetchrow($result)) ? doubleval($row['sum_filesize']) : 0;
		$db->sql_freeresult($result);

		$units = array();
		$filesize_upload_unit = size_get_units($filesize_upload_value, $units);
		$filesize_upload = round($filesize_upload_value / max(1, $filesize_upload_unit), 2) . ' ' . $user->lang($units[$filesize_upload_unit]);

		// then we display the quota block
		$template->assign_block_vars('attach_quota', array(
			'L_QUOTA' => sprintf($user->lang('User_quota_profile'), $filesize_limit),
			'L_UPLOADED' => sprintf($user->lang('User_uploaded_profile'), $filesize_upload),
			'QUOTA_BOX' => get_quota_box('Upload_percent_profile', $filesize_upload_value, $filesize_limit_value),
		));
		$template->assign_block_vars('cp_menus', array('BOX' => $template->include_file('ucp/ucp_attach_quota_box.tpl', array('attach_quota'))));
	}

	function get_link_parms()
	{
		global $dft_sort, $dft_order;

		$parms = $this->parms;
		if ( $this->fields['sort']->value != $dft_sort )
		{
			$parms['sort'] = $this->fields['sort']->value;
		}
		if ( $this->fields['order']->value != $dft_order )
		{
			$parms['order'] = $this->fields['order']->value;
		}

		if ( trim($this->fields['filename']->value) != '' )
		{
			$parms['filename'] = rawurlencode($this->fields['filename']->value);
		}
		if ( trim($this->fields['file_comment']->value) != '' )
		{
			$parms['file_comment'] = rawurlencode($this->fields['file_comment']->value);
		}
		if ( intval($this->fields['sizemin']->value) )
		{
			$parms['sizemin'] = intval($this->fields['sizemin']->value);
		}
		if ( intval($this->fields['sizemax']->value) )
		{
			$parms['sizemax'] = intval($this->fields['sizemax']->value);
		}
		if ( intval($this->fields['countmin']->value) )
		{
			$parms['countmin'] = intval($this->fields['countmin']->value);
		}
		if ( intval($this->fields['countmax']->value) )
		{
			$parms['countmax'] = intval($this->fields['countmax']->value);
		}
		if ( intval($this->fields['topicdays']->value) )
		{
			$parms['topicdays'] = intval($this->fields['topicdays']->value);
		}
		return $parms;
	}

	function read()
	{
		global $db, $config, $user, $forums;
		global $sort_fields, $order_fields;
		global $view_user;

		$this->data = array();
		$this->total = 0;
		$this->now = time();

		// get authorised forums
		$forum_ids = array();
		if ( !empty($forums->data) )
		{
			foreach ( $forums->data as $forum_id => $data )
			{
				if ( $user->auth(POST_FORUM_URL, 'auth_download', $forum_id) || $user->auth(POST_FORUM_URL, 'auth_mod', $forum_id) )
				{
					$forum_ids[] = $forum_id;
				}
			}
		}

		// buid the where selection
		$filename = preg_replace('/\*/', '%', $this->fields['filename']->value);
		$filename = trim(str_replace('%', '', $filename)) == '' ? '' : $filename;

		$file_comment = preg_replace('/\*/', '%', $this->fields['file_comment']->value);
		$file_comment = trim(str_replace('%', '', $file_comment)) == '' ? '' : $file_comment;

		$author = preg_replace('/\*/', '%', isset($this->fields['author']) ? $this->fields['author']->value : '');
		$author = trim(str_replace('%', '', $author)) == '' ? '' : $author;

		$size_min = $this->fields['sizemin']->value;
		$size_max = $this->fields['sizemax']->value;

		$download_min = $this->fields['countmin']->value;
		$download_max = $this->fields['countmax']->value;

		$topicdays = $this->fields['topicdays']->value;

		$sql_where = array();
		if ( !empty($filename) )
		{
			$sql_where[] = 'd.real_filename LIKE \'' . $db->sql_escape_string($filename) . '\'';
		}
		if ( !empty($file_comment) )
		{
			$sql_where[] = 'd.file_comment LIKE \'' . $db->sql_escape_string($file_comment) . '\'';
		}
		if ( !empty($size_min) )
		{
			$sql_where[] = 'd.filesize > ' . intval($size_min);
		}
		if ( !empty($size_max) )
		{
			$sql_where[] = 'd.filesize <= ' . intval($size_max);
		}
		if ( !empty($download_min) )
		{
			$sql_where[] = 'd.download_count > ' . intval($download_min);
		}
		if ( !empty($download_max) )
		{
			$sql_where[] = 'd.download_count <= ' . intval($download_max);
		}
		if ( !empty($topicdays) )
		{
			$sql_where[] = 'd.filetime > ' . ($this->now - (intval($topicdays) * 86400));
		}

		// get all attachments with pms the user have : we'll bet they are not too numerous ;)
		$privmsgs_id = array();
		$from_user = array(PRIVMSGS_SENT_MAIL, PRIVMSGS_NEW_MAIL, PRIVMSGS_SAVED_OUT_MAIL);
		$to_user = array(PRIVMSGS_READ_MAIL, PRIVMSGS_NEW_MAIL, PRIVMSGS_UNREAD_MAIL, PRIVMSGS_SAVED_IN_MAIL);
		$sql = 'SELECT privmsgs_id, privmsgs_type
					FROM ' . PRIVMSGS_TABLE . '
					WHERE privmsgs_attachment = 1
						AND ((privmsgs_from_userid = ' . intval($view_user->data['user_id']) . ' AND privmsgs_type IN(' . implode(', ', $from_user) . '))
							OR (privmsgs_to_userid = ' . intval($view_user->data['user_id']) . ' AND privmsgs_type IN(' . implode(', ', $to_user) . ')))';
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		while ( $row = $db->sql_fetchrow($result) )
		{
			$privmsgs_ids[ intval($row['privmsgs_id']) ] = intval($row['privmsgs_type']);
		}
		$db->sql_freeresult($result);

		// no forums authorised : we don't need the posts
		if ( empty($forum_ids) )
		{
			if ( empty($privmsgs_ids) )
			{
				$this->total = 0;
			}
			else
			{
				$sql = 'SELECT d.*, a.post_id, a.privmsgs_id, a.user_id
							FROM ' . ATT_LINKS_TABLE . ' a
								LEFT JOIN ' . ATT_DESC_TABLE . ' d
									ON d.attach_id = a.attach_id
							WHERE a.privmsgs_id IN(' . implode(', ', array_keys($privmsgs_ids)) . ')' . (empty($sql_where) ? '' : '
								AND ' . implode('
								AND ', $sql_where));
				$result = $db->sql_query($sql, false, __LINE__, __FILE__);
				$this->total = $db->sql_numrows($result);
				$db->sql_freeresult($result);
			}
		}
		// some forums are authorised : we need the posts
		else
		{
			$sql = 'SELECT d.*, a.post_id, a.privmsgs_id, a.user_id, p.forum_id, p.topic_id
						FROM ' . ATT_LINKS_TABLE . ' a
							LEFT JOIN ' . POSTS_TABLE . ' p
								ON a.post_id <> 0
									AND a.user_id = ' . intval($view_user->data['user_id']) . '
									AND p.post_id = a.post_id
									AND p.forum_id IN(' . implode(', ', $forum_ids) . ')
							LEFT JOIN ' . ATT_DESC_TABLE . ' d
								ON d.attach_id = a.attach_id
						WHERE ' . (empty($privmsgs_ids) ? '' : '(') . 'p.post_id IS NOT NULL' . (empty($privmsgs_ids) ? '' : '
								OR a.privmsgs_id IN(' . implode(', ', array_keys($privmsgs_ids)) . '))') . (empty($sql_where) ? '' : '
							AND ' . implode('
							AND ', $sql_where));
			$result = $db->sql_query($sql, false, __LINE__, __FILE__);
			$this->total = $db->sql_numrows($result);
			$db->sql_freeresult($result);
		}

		if ( $this->total )
		{
			// get sort and order
			$sort_field = $sort_fields[ $this->fields['sort']->value ];
			$order_field = $order_fields[ $this->fields['order']->value ];

			$post_ids = array();
			$sql .= '
					ORDER BY ' . $sort_field . $order_field . ', d.attach_id DESC
					LIMIT ' . $this->start . ', ' . $this->ppage;
			$result = $db->sql_query($sql, false, __LINE__, __FILE__);
			$i = 0;
			while ( $row = $db->sql_fetchrow($result) )
			{
				if ( intval($row['post_id']) )
				{
					if ( !isset($post_ids[ intval($row['post_id']) ]) )
					{
						$post_ids[ intval($row['post_id']) ] = array($i);
					}
					else
					{
						$post_ids[ intval($row['post_id']) ][] = $i;
					}
				}
				if ( ($privmsgs_id = intval($row['privmsgs_id'])) && isset($privmsgs_ids[$privmsgs_id]) )
				{
					$row['privmsgs_type'] = $privmsgs_ids[$privmsgs_id];
				}
				$this->data[$i] = $row;
				$i++;
			}
			$db->sql_freeresult($result);

			// get topics title
			if ( !empty($post_ids) )
			{
				$sql = 'SELECT p.post_id, t.topic_title
							FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t
							WHERE t.topic_id = p.topic_id
								AND p.post_id IN(' . implode(', ', array_keys($post_ids)) . ')';
				$result = $db->sql_query($sql, false, __LINE__, __FILE__);
				while ( $row = $db->sql_fetchrow($result) )
				{
					$count_attach = count($post_ids[ intval($row['post_id']) ]);
					for ( $i = 0; $i < $count_attach; $i++ )
					{
						$this->data[ $post_ids[ intval($row['post_id']) ][$i] ]['topic_title'] = $row['topic_title'];
					}
				}
				$db->sql_freeresult($result);
			}
		}
	}
}

// process
$parms = array(
	'mode' => $menu_id,
	'sub' => $subm_id == $menu_id ? '' : $subm_id,
	'ctx' => $ctx_id == $subm_id ? '' : $ctx_id,
);
$form = new attach_cp($cp_requester, $cp_parms + $parms, $fields);
$form->process();
$template->set_filenames(array('body' => 'cp_generic.tpl'));

?>